<template>
  <el-dialog
    v-model="dialogVisible"
    :title="isNewAnnotation ? '添加标注点' : '编辑标注点'"
    width="500px"
    :close-on-click-modal="false"
    :close-on-press-escape="true"
    @close="handleClose"
  >
    <el-form 
      ref="formRef"
      :model="formData" 
      :rules="formRules"
      label-width="80px" 
      class="thin-scrollbar"
    >
      <el-form-item label="建筑名称" prop="buildingName">
        <el-input
          v-model="formData.buildingName"
          placeholder="请输入标建筑名称"
          maxlength="50"
          show-word-limit
          clearable
        />
      </el-form-item>
      
      <el-form-item label="建筑地址">
        <el-input
          v-model="formData.buildingAddress"
          type="textarea"
          placeholder="请输入建筑地址"
          :rows="4"
          maxlength="200"
          show-word-limit
          resize="none"
        />
      </el-form-item>
      <el-form-item label="建筑介绍">
        <el-input
          v-model="formData.buildingIntroduction"
          type="textarea"
          placeholder="请输入建筑介绍"
          :rows="4"
          maxlength="200"
          show-word-limit
          resize="none"
        />
      </el-form-item>
      <el-form-item label="建筑图片">
        <el-upload
          class="upload-demo"
          :show-file-list="false"
          accept="image/*"
          :limit="1"
          action="#"
          :http-request="uploadImage"
        >
        <img style="width: 170px;height: 170px;object-fit: contain;" v-if="formData.imageUrl" :src="formData.imageUrl" class="avatar" />
        <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="X坐标" prop="left">
        <el-input-number
          v-model="formData.left"
          :min="0"
          :max="100"
          :precision="2"
          :step="0.1"
          controls-position="right"
          style="width: 100%"
        />
        <div class="form-tip">相对于图片左边的百分比位置</div>
      </el-form-item>
      
      <el-form-item label="Y坐标" prop="top">
        <el-input-number
          v-model="formData.top"
          :min="0"
          :max="100"
          :precision="2"
          :step="0.1"
          controls-position="right"
          style="width: 100%"
        />
        <div class="form-tip">相对于图片顶部的百分比位置</div>
      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <div class="footer-left">
          <el-button 
            v-if="!isNewAnnotation && allowDelete" 
            type="danger" 
            plain
            @click="handleDelete"
            :loading="deleteLoading"
          >
            <el-icon><Delete /></el-icon>
            删除标注点
          </el-button>
        </div>
        <div class="footer-right">
          <el-button @click="handleCancel" :disabled="saveLoading">
            取消
          </el-button>
          <el-button 
            type="primary" 
            @click="handleSave"
            :loading="saveLoading"
          >
            {{ isNewAnnotation ? '添加' : '保存' }}
          </el-button>
        </div>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import { Delete } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { fileApi } from '@/api'
export default {
  name: 'AnnotationEditForm',
  components: {
    Delete
  },
  props: {
    // 控制对话框显示
    visible: {
      type: Boolean,
      default: false
    },
    // 初始表单数据
    initialData: {
      type: Object,
      default: () => ({
        id: null,
        title: '',
        description: '',
        left: 0,
        top: 0
      })
    },
    // 是否为新建标注
    isNew: {
      type: Boolean,
      default: true
    },
    // 是否允许删除
    allowDelete: {
      type: Boolean,
      default: true
    }
  },
  emits: ['update:visible', 'save', 'delete', 'cancel'],
  data() {
    return {
      dialogVisible: false,
      saveLoading: false,
      deleteLoading: false,
      formData: {
        buildingName: '',
        left: 0,
        top: 0,
        dynamicFieldJson: {
          address: '',
          description: '',
          imageUrl: '',
          left: 0,
          top: 0,
        }
      },
      formRules: {
        buildingName: [
          { required: true, message: '请输入建筑名称', trigger: 'blur' },
          { min: 1, max: 50, message: '标题长度在 1 到 50 个字符', trigger: 'blur' }
        ],
        description: [
          { max: 200, message: '描述不能超过 200 个字符', trigger: 'blur' }
        ],
        left: [
          { required: true, message: '请输入X坐标', trigger: 'blur' },
          { type: 'number', min: 0, max: 100, message: 'X坐标必须在 0-100 之间', trigger: 'blur' }
        ],
        top: [
          { required: true, message: '请输入Y坐标', trigger: 'blur' },
          { type: 'number', min: 0, max: 100, message: 'Y坐标必须在 0-100 之间', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    isNewAnnotation() {
      return this.isNew || !this.formData.id
    }
  },
  watch: {
    visible: {
      handler(newVal) {
        this.dialogVisible = newVal
        // if (newVal) {
        //   this.initFormData()
        // }
      },
      immediate: true
    },
    dialogVisible(newVal) {
      this.$emit('update:visible', newVal)
    },
    initialData: {
      handler(val) {
        console.log('initialData', val)
        if (this.dialogVisible) {
          this.initFormData()
        }
      },
      deep: true
    }
  },
  methods: {
    async uploadImage(val) {
      console.log("wenjian, val", val)
      const res = await fileApi.upload(val.file)
      console.log("上传完成", res)
      this.formData.imageUrl = res.data
    },
    // 初始化表单数据
    initFormData() {
      this.formData = {
        // buildingName: '',
        // description: '',
        // imageUrl: '',
        ...this.initialData,
        imageUrl: this.initialData.buildingImgUrl || '',
        left: this.initialData.left - 0 || 0,
        top: this.initialData.top - 0 || 0
      }
      // 清除验证状态
      this.$nextTick(() => {
        if (this.$refs.formRef) {
          this.$refs.formRef.clearValidate()
        }
      })
    },

    // 重置表单
    resetForm() {
      this.formData = {
        title: '',
        description: '',
        left: 0,
        top: 0
      }
      if (this.$refs.formRef) {
        this.$refs.formRef.clearValidate()
      }
    },

    // 验证表单
    async validateForm() {
      try {
        await this.$refs.formRef.validate()
        return true
      } catch (error) {
        return false
      }
    },

    // 处理保存
    async handleSave() {
      const isValid = await this.validateForm()
      if (!isValid) {
        ElMessage.warning('请检查表单输入')
        return
      }

      this.saveLoading = true
      try {
        // 发送保存事件，传递表单数据
        this.$emit('save', {
          ...this.formData,
          isNew: this.isNewAnnotation
        })
      } finally {
        this.saveLoading = false
      }
    },

    // 处理删除
    handleDelete() {
      if (!this.formData.id) return

      ElMessageBox.confirm(
        `确定要删除标注点"${this.formData.buildingName}"吗？此操作不可恢复！`,
        '删除确认',
        {
          confirmButtonText: '确定删除',
          cancelButtonText: '取消',
          type: 'warning',
          dangerouslyUseHTMLString: false,
          // customClass: 'delete-confirm-dialog'
        }
      ).then(() => {
        this.deleteLoading = true
        try {
          // 发送删除事件
          this.$emit('delete', this.formData.id)
        } finally {
          this.deleteLoading = false
        }
      }).catch(() => {
        // 用户取消删除
      })
    },

    // 处理取消
    handleCancel() {
      this.handleClose()
    },

    // 处理关闭
    handleClose() {
      this.dialogVisible = false
      this.resetForm()
      this.$emit('cancel')
    },

    // 外部调用：关闭对话框
    close() {
      this.handleClose()
    },

    // 外部调用：显示成功消息并关闭
    showSuccessAndClose(message = '操作成功') {
      ElMessage.success(message)
      this.close()
    },

    // 外部调用：显示错误消息
    showError(message = '操作失败') {
      ElMessage.error(message)
    }
  }
}
</script>

<style scoped>
.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
  line-height: 1.4;
}
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.avatar-uploader .el-upload {
  border: 1px dashed  #000;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: #000;
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
/* 对话框底部样式 */
.dialog-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.footer-left {
  flex: 1;
}

.footer-right {
  display: flex;
  gap: 10px;
}

/* 删除按钮样式优化 */
.footer-left .el-button {
  border-color: #f56c6c;
  color: #f56c6c;
}

.footer-left .el-button:hover {
  background-color: #f56c6c;
  border-color: #f56c6c;
  color: white;
}

.footer-left .el-button:focus {
  border-color: #f56c6c;
  color: #f56c6c;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .dialog-footer {
    flex-direction: column;
    gap: 15px;
  }

  .footer-left {
    width: 100%;
    order: 2;
  }

  .footer-right {
    width: 100%;
    order: 1;
    justify-content: flex-end;
  }

  .footer-left .el-button {
    width: 100%;
  }
}
</style>
